Skip to content

fix: add logging to POST /api/sandboxes#411

Closed
sweetmantech wants to merge 3 commits intotestfrom
fix/sandbox-post-logging
Closed

fix: add logging to POST /api/sandboxes#411
sweetmantech wants to merge 3 commits intotestfrom
fix/sandbox-post-logging

Conversation

@sweetmantech
Copy link
Copy Markdown
Contributor

@sweetmantech sweetmantech commented Apr 7, 2026

Summary

  • Adds console.error logging when validation/auth fails in the POST handler (logs the error body)
  • Adds console.error logging when sandbox creation throws an exception
  • Adds console.log for sandbox creation params to trace what's being sent to Sandbox.create

Both sidney@recoupable.com and sidney+1@recoupable.com are hitting errors on POST /api/sandboxes with no visibility in Vercel function logs. This PR adds the logging needed to diagnose the root cause.

Test plan

  • Deploy preview and have Sidney hit POST /api/sandboxes
  • Check Vercel function logs for the new [POST /api/sandboxes] log lines
  • Identify root cause from logs and follow up with a fix

🤖 Generated with Claude Code


Summary by cubic

Add server-side logging to POST /api/sandboxes so validation/auth failures and sandbox creation errors show in Vercel logs. Also log sandbox params in createSandbox, API key diagnostics in getApiKeyAccountId (prefix, hash, match count), and snapshot lookup, fallback, and insert errors in processCreateSandbox.

Written for commit 8a08a90. Summary will update on new commits.

Summary by CodeRabbit

  • Chores
    • Enhanced diagnostic logging across sandbox workflows and request handling to improve observability and error tracking.
    • Added additional diagnostic output for failure paths during sandbox creation requests.
    • Added masked/logged API key diagnostics and counts to aid troubleshooting without exposing full keys.

Both validation/auth failures and sandbox creation errors were being
returned as JSON responses without any server-side logging, making it
impossible to diagnose issues from Vercel function logs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@vercel
Copy link
Copy Markdown
Contributor

vercel bot commented Apr 7, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
recoup-api Ready Ready Preview Apr 7, 2026 4:15pm

Request Review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 7, 2026

Warning

Rate limit exceeded

@sweetmantech has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 18 minutes and 56 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 18 minutes and 56 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d465484b-ae68-4e8a-9cba-eb6ef249f27d

📥 Commits

Reviewing files that changed from the base of the PR and between 83113de and 8a08a90.

📒 Files selected for processing (1)
  • lib/sandbox/processCreateSandbox.ts
📝 Walkthrough

Walkthrough

Added non-functional runtime logging: input params logged during sandbox creation, validation/exception responses logged in the sandbox post handler, and masked API-key, key hash, and matched-key count logged in API key lookup. No exported signatures or control-flow outcomes were changed.

Changes

Cohort / File(s) Summary
Sandbox creation / post-handler
lib/sandbox/createSandbox.ts, lib/sandbox/createSandboxPostHandler.ts
Inserted console logging: createSandbox now logs the incoming params before calling Sandbox.create; createSandboxPostHandler logs cloned validation response bodies and caught errors on failure paths.
API key lookup logging
lib/auth/getApiKeyAccountId.ts
Added console logs in success path to emit a masked x-api-key prefix, the computed keyHash, and the count (or null) of matched apiKeys returned by selectAccountApiKeys.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

Poem

In the logs a whisper starts to play,
Params and keys now greet the day,
When handlers stumble, traces show,
Small lights reveal what they must know,
Quiet clues that point the way ✨

🚥 Pre-merge checks | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Solid & Clean Code ⚠️ Warning PR adds diagnostic logging directly into business logic functions, violating Single Responsibility Principle and embedding temporary debugging code as permanent. Guard logging behind environment variables, extract into separate logger utility via dependency injection, address security concerns with API key exposure, and mark as temporary with TODO comments.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/sandbox-post-logging

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
lib/sandbox/createSandbox.ts (1)

40-40: Consider potential sensitive data in logged params.

The CreateSandboxParams object could contain environment variables or other sensitive configuration in the source property. While this logging is useful for debugging, ensure that callers don't inadvertently pass secrets in the params that would then appear in Vercel function logs.

If this is temporary debugging code intended to be removed after diagnosing Sidney's issue, consider adding a // TODO: remove after debugging comment to signal intent.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/sandbox/createSandbox.ts` at line 40, The console.log in createSandbox
that prints JSON.stringify(params) may leak secrets (notably params.source);
replace it with safer logging: either remove the log, redact sensitive keys
(e.g., mask params.source, env, secrets) before logging, or wrap it with a
temporary TODO comment indicating it's for debugging and must be removed; update
the log call in the createSandbox function to only emit non-sensitive fields or
a redacted summary and add a "// TODO: remove after debugging" comment if
keeping it temporarily.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@lib/sandbox/createSandbox.ts`:
- Line 40: The console.log in createSandbox that prints JSON.stringify(params)
may leak secrets (notably params.source); replace it with safer logging: either
remove the log, redact sensitive keys (e.g., mask params.source, env, secrets)
before logging, or wrap it with a temporary TODO comment indicating it's for
debugging and must be removed; update the log call in the createSandbox function
to only emit non-sensitive fields or a redacted summary and add a "// TODO:
remove after debugging" comment if keeping it temporarily.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0a5ac450-99cf-4eba-bae4-85b1fa776a26

📥 Commits

Reviewing files that changed from the base of the PR and between 85fa5b8 and 0d10b1e.

📒 Files selected for processing (2)
  • lib/sandbox/createSandbox.ts
  • lib/sandbox/createSandboxPostHandler.ts

Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 2 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Auto-approved: This PR only adds diagnostic logging to assist with debugging, which has no impact on business logic or system behavior.

Architecture diagram
sequenceDiagram
    participant Client
    participant Handler as POST Handler
    participant Validator as Body Validator
    participant SDK as Sandbox SDK
    participant Logs as Vercel Logs

    Client->>Handler: POST /api/sandboxes
    Handler->>Validator: validateSandboxBody(request)
    
    alt Validation or Auth Fails
        Validator-->>Handler: NextResponse (Error)
        Handler->>Logs: NEW: console.error([POST /api/sandboxes] Validation/auth failed)
        Handler-->>Client: 4xx/401 Response
    else Validation Success
        Validator-->>Handler: Validated Data
        Handler->>SDK: createSandbox(params)
        
        Note over SDK,Logs: Logging inputs for debugging
        SDK->>Logs: NEW: console.log([createSandbox] Creating sandbox with params)
        
        SDK->>SDK: Sandbox.create(params)
        
        alt Creation Success
            SDK-->>Handler: Sandbox Object
            Handler-->>Client: 200 OK
        else Exception Caught
            SDK-->>Handler: Throw Error
            Handler->>Logs: NEW: console.error([POST /api/sandboxes] Error creating sandbox)
            Handler-->>Client: 500 Error Response
        end
    end
Loading

Logs key prefix, computed hash, and match count to help diagnose
why prod API key lookups return no results.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
lib/auth/getApiKeyAccountId.ts (1)

14-79: Function exceeds 50-line guideline (currently ~66 lines).

Per the coding guidelines, domain functions in lib/**/*.ts should stay under 50 lines. While this predates the current PR, the added logging is a good opportunity to consider extracting the error-response logic into a small helper (e.g., buildAuthErrorResponse(message, status)) to reduce repetition and line count.

Not blocking, but worth considering for maintainability.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/auth/getApiKeyAccountId.ts` around lines 14 - 79, getApiKeyAccountId is
over the 50-line limit due to repeated error-response boilerplate; extract a
small helper (e.g., buildAuthErrorResponse(message: string, status: number):
NextResponse) and replace the three JSON error returns inside getApiKeyAccountId
(the missing x-api-key branch, the Unauthorized branch, and the catch/500 branch
that also handles selectAccountApiKeys null) with calls to this helper, keeping
existing use of getCorsHeaders(), and leave hashing/logging and the
selectAccountApiKeys call intact to reduce lines and duplication.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/auth/getApiKeyAccountId.ts`:
- Around line 32-35: In getApiKeyAccountId, stop logging sensitive portions of
the API key and hash: replace the apiKey.slice(0,12) log with a masked form
showing only the last 4 characters (e.g., "..." + apiKey.slice(-4)) and log only
a truncated hash prefix (e.g., keyHash.slice(0,8) + "..."); gate all diagnostic
console.log calls (the ones referencing apiKey and keyHash and the matched keys
count around selectAccountApiKeys) behind an environment flag like DEBUG_AUTH so
they only run when enabled, and add a TODO comment "// TODO: Remove diagnostic
logging after `#411` investigation" next to the gated logs for cleanup tracking.

---

Nitpick comments:
In `@lib/auth/getApiKeyAccountId.ts`:
- Around line 14-79: getApiKeyAccountId is over the 50-line limit due to
repeated error-response boilerplate; extract a small helper (e.g.,
buildAuthErrorResponse(message: string, status: number): NextResponse) and
replace the three JSON error returns inside getApiKeyAccountId (the missing
x-api-key branch, the Unauthorized branch, and the catch/500 branch that also
handles selectAccountApiKeys null) with calls to this helper, keeping existing
use of getCorsHeaders(), and leave hashing/logging and the selectAccountApiKeys
call intact to reduce lines and duplication.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: cfaa5d7e-6267-474a-afeb-21944c81982d

📥 Commits

Reviewing files that changed from the base of the PR and between 0d10b1e and 83113de.

📒 Files selected for processing (1)
  • lib/auth/getApiKeyAccountId.ts

Comment on lines +32 to +35
console.log("[getApiKeyAccountId] key prefix:", apiKey.slice(0, 12) + "...");
console.log("[getApiKeyAccountId] hash:", keyHash);
const apiKeys = await selectAccountApiKeys({ keyHash });
console.log("[getApiKeyAccountId] matched keys:", apiKeys?.length ?? "null");
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Security concern: Logging 12 characters of an API key exposes too much of the secret.

Logging apiKey.slice(0, 12) reveals a significant portion of the credential. Depending on key format and entropy distribution, this could meaningfully narrow down the key space or violate compliance policies around secrets in logs (Vercel logs may be accessible to broader teams).

Additionally, logging the full keyHash enables cross-log correlation and could theoretically aid offline attacks if the key space is constrained.

Recommendations:

  1. Mask more aggressively—show only the last 4 characters: "..." + apiKey.slice(-4)
  2. Consider gating this diagnostic logging behind an environment variable (e.g., DEBUG_AUTH=true) so it doesn't persist in production once the issue is resolved.
  3. Add a // TODO: Remove diagnostic logging after fix: add logging to POST /api/sandboxes #411 investigation comment to ensure cleanup.
🔒 Proposed safer masking
-    console.log("[getApiKeyAccountId] key prefix:", apiKey.slice(0, 12) + "...");
-    console.log("[getApiKeyAccountId] hash:", keyHash);
+    // TODO: Remove diagnostic logging after `#411` investigation
+    console.log("[getApiKeyAccountId] key suffix:", "..." + apiKey.slice(-4));
     const apiKeys = await selectAccountApiKeys({ keyHash });
-    console.log("[getApiKeyAccountId] matched keys:", apiKeys?.length ?? "null");
+    console.log("[getApiKeyAccountId] matched keys:", apiKeys?.length ?? "null");

If you need the hash for correlation, consider logging only a truncated portion:

console.log("[getApiKeyAccountId] hash prefix:", keyHash.slice(0, 8) + "...");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/auth/getApiKeyAccountId.ts` around lines 32 - 35, In getApiKeyAccountId,
stop logging sensitive portions of the API key and hash: replace the
apiKey.slice(0,12) log with a masked form showing only the last 4 characters
(e.g., "..." + apiKey.slice(-4)) and log only a truncated hash prefix (e.g.,
keyHash.slice(0,8) + "..."); gate all diagnostic console.log calls (the ones
referencing apiKey and keyHash and the matched keys count around
selectAccountApiKeys) behind an environment flag like DEBUG_AUTH so they only
run when enabled, and add a TODO comment "// TODO: Remove diagnostic logging
after `#411` investigation" next to the gated logs for cleanup tracking.

Logs snapshot ID resolution, snapshot vs fresh creation failures,
and insertAccountSandbox errors to trace the exact failure point.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 1 file (changes from recent commits).

Auto-approved: The PR only adds diagnostic logging and error reporting to the sandbox creation flow to debug existing issues. Low risk and does not modify business logic.

@sweetmantech
Copy link
Copy Markdown
Contributor Author

Superseded by #412 which includes the fix and proper logging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant